import React, { useState } from 'react';
import {
  Button,
  Card,
  Col,
  Input,
  message,
  Radio,
  Row,
  Space,
  Table,
  Tooltip,
} from 'antd';
import KPageHeader from '@/components/KPageHeader';
import {
  CloseOutlined,
  InfoCircleOutlined,
  PlusOutlined,
  CopyOutlined,
  FileWordOutlined,
} from '@ant-design/icons';
import styles from './style.module.less';
import { useDynamicList, useRequest } from 'ahooks';
import { history } from 'umi';
import { RandomStr } from '@/utils/random';
import { apiSystemUsers } from '@/api/system/users.api';
import { ColumnType } from 'antd/es/table';
import copy from 'copy-to-clipboard';
import json2csv from 'json2csv';

interface FormUserRow {
  username?: string;
  nickname?: string;
  password?: string;
}

interface FormUserCreateSuccess extends API.FormUserCreate {
  state: string;
}

// 账号创建成功结果页
const CreateAtSuccess = (props: { users: FormUserCreateSuccess[] }) => {
  // 复制账号信息
  const onClickCopy = (record: FormUserCreateSuccess) => {
    if (
      copy(
        `称呼：${record.nickname}\r\n账号：${record.username}\r\n密码：${record.password}`,
      )
    ) {
      message.success('复制成功');
    } else {
      message.error('复制失败');
    }
  };

  // 导出到csv
  const onExport = () => {
    const csv = json2csv.parse(props.users, {
      fields: [
        { label: '登录名', value: 'username' },
        { label: '显示名', value: 'nickname' },
      ],
    });
    const b = new Blob([csv], { type: 'text/plain' });
    const url = URL.createObjectURL(b);
    const a = document.createElement('a');
    if (!a) {
      return;
    }
    a.setAttribute('href', url);
    a.setAttribute('download', '账号信息.csv');
    a.click();
  };

  const columns: ColumnType<FormUserCreateSuccess>[] = [
    { title: '登录名', dataIndex: 'username' },
    { title: '密码', dataIndex: 'password' },
    { title: '显示名称', dataIndex: 'nickname' },
    { title: '状态', dataIndex: 'state' },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <div>
          <Button
            type={'link'}
            icon={<CopyOutlined />}
            onClick={() => onClickCopy(record)}
          >
            复制
          </Button>
        </div>
      ),
    },
  ];
  return (
    <Card>
      <h3>账号信息</h3>

      <div style={{ margin: '10px 0' }}>
        <Button icon={<FileWordOutlined />} onClick={onExport}>
          导出到CSV
        </Button>
      </div>

      <div>
        <Table
          rowKey={'username'}
          size={'small'}
          columns={columns}
          dataSource={props.users}
          pagination={false}
        />
      </div>
    </Card>
  );
};

// 账号输入框
const UserInputRow = (props: {
  showClose: boolean;
  onRemove: () => void;
  username: string;
  nickname: string;
  onChange: (col: string, val: string) => void;
}) => {
  return (
    <div className={styles.userInputRow}>
      <div className={styles.userInputRowCol}>
        <Input
          value={props.username}
          onChange={e => props.onChange('username', e.target.value)}
        />
      </div>

      <div className={styles.userInputRowCol}>
        <Input
          value={props.nickname}
          onChange={e => props.onChange('nickname', e.target.value)}
        />
      </div>

      <div className={styles.userInputRowRight}>
        {props.showClose && <CloseOutlined onClick={props.onRemove} />}
      </div>
    </div>
  );
};

export default () => {
  const [hasSuccess, setSuccess] = useState(false);
  const [users, setUsers] = useState<FormUserCreateSuccess[]>([]);
  const { run: submitRequest, loading: subIng } = useRequest(
    apiSystemUsers.createUsers,
    {
      manual: true,
      onSuccess: () => {
        setSuccess(true);
      },
    },
  );
  const { list, remove, push, replace } = useDynamicList<FormUserRow>([{}]);
  const [passwordType, setPasswordType] = useState(0);
  const [password, setPassword] = useState('');

  // 表单提交
  const onFormSubmit = () => {
    const users: API.FormUserCreate[] = [];
    list.forEach(user => {
      users.push({
        username: user.username ?? '',
        nickname: user.nickname ?? '',
        password: passwordType === 0 ? RandomStr(8) : password,
      });
    });
    setUsers(
      users.map(user => ({
        ...user,
        state: '成功',
      })),
    );
    return submitRequest(users);
  };

  return (
    <>
      <KPageHeader title={'创建管理员'} />

      {hasSuccess && <CreateAtSuccess users={users} />}

      {!hasSuccess && (
        <Card>
          <div className={styles.formTitle}>
            <label>用户账号信息</label>
          </div>

          <div className={styles.userInputRow}>
            <div className={styles.userInputRowCol}>
              <div className={styles.userInputRowLabel}>
                <i>*</i>登录名称
                <Tooltip
                  title={'格式为英文字母、数字、.、_或-，最多包含 64 个字符。'}
                  color={'green'}
                >
                  <InfoCircleOutlined />
                </Tooltip>
              </div>
            </div>

            <div className={styles.userInputRowCol}>
              <div className={styles.userInputRowLabel}>
                <i>*</i>显示名称
                <Tooltip title={'最多包含 128 个字符或汉字。'} color={'green'}>
                  <InfoCircleOutlined />
                </Tooltip>
              </div>
            </div>

            <div className={styles.userInputRowRight} />
          </div>

          {list.map((item, idx) => (
            <UserInputRow
              key={idx}
              showClose={list.length > 1}
              username={item.username ?? ''}
              nickname={item.nickname ?? ''}
              onChange={(col, val) => {
                replace(idx, {
                  ...item,
                  [col]: val,
                });
              }}
              onRemove={() => remove(idx)}
            />
          ))}

          <div style={{ marginTop: 10 }}>
            <Button
              icon={<PlusOutlined />}
              size={'small'}
              type={'link'}
              onClick={() => push({})}
            >
              添加用户
            </Button>
          </div>

          <div className={styles.formTitle}>
            <label>登录密码</label>
          </div>

          <div>
            <Radio.Group
              value={passwordType}
              onChange={e => setPasswordType(e.target.value)}
            >
              <Space direction={'vertical'}>
                <Radio value={0}>系统生成</Radio>
                <Radio value={1}>自定义密码</Radio>
              </Space>
            </Radio.Group>

            {passwordType === 1 && (
              <div style={{ marginTop: 10, maxWidth: 300 }}>
                <Input
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                />
              </div>
            )}
          </div>

          <div style={{ marginTop: 20 }}>
            <Space>
              <Button
                type={'primary'}
                loading={subIng}
                onClick={() => onFormSubmit()}
              >
                确定
              </Button>
              <Button onClick={() => history.goBack()}>返回</Button>
            </Space>
          </div>
        </Card>
      )}
    </>
  );
};
